package com.crowdfunding.backend;

import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class AppInitializer {

    @Bean
    public ApplicationRunner createDataDir(org.springframework.jdbc.core.JdbcTemplate jdbc) {
        return args -> {
            File f = new File(System.getProperty("user.dir"), "backend-spring/data");
            if (!f.exists()) {
                f.mkdirs();
            }
            // ensure users table exists (useful if schema.sql didn't run)
            String sql = "CREATE TABLE IF NOT EXISTS users ("+
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, "+
                    "username TEXT NOT NULL UNIQUE, "+
                    "email TEXT NOT NULL UNIQUE, "+
                    "password_hash TEXT NOT NULL, "+
                    "eoa_address TEXT, "+
                    "created_at INTEGER NOT NULL"+
                    ");";
            try {
                jdbc.execute(sql);
            } catch (Exception e) {
                System.err.println("Failed to ensure users table: " + e.getMessage());
            }
        };
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins("http://localhost:8080", "http://localhost:8082").allowedMethods("GET","POST","PUT","DELETE").allowCredentials(true);
            }
        };
    }
}
